/**
 * Created by JetBrains WebStorm.
 * User: Alexander.Rusanov
 * Date: 22.11.11
 * Time: 11:58
 * To change this template use File | Settings | File Templates.
 */
var sso_url = 'http://www.teamlab.info/sso/Account/Auth';
var store = null;
var store_key = 'logins';
var isOnline = false;
var wasMoved = 0;
var eventTimestamp = 200;
var startEventTimestamp = 0;
var startClickedObject = null;
var $wrapper = $('#pageWrapper');
var drTimeout = 0, cpTimeout1 = 0, cpTimeout2 = 0, taTimeout = 0;
var userLogin = '', userPassword = '';
var mobileClient = null;

var touchClick = 'click';
var touchStartEvent = 'ontouchend' in document ? 'touchstart' : 'mousedown';
var touchStopEvent  = 'ontouchend' in document ? 'touchend' : 'mouseup';
var touchMoveEvent = 'ontouchend' in document ? 'touchmove' : 'mousemove';

var statusMessages = {
  '-1'  : {
    title : 'Some error',
    text  : 'Get some error.'
  },
  '0'   : {
    title : 'No internet connection',
    text  : 'Check your internet connection.'
  },
  '400' : {
    title : 'Bad Request',
    text  : 'The request cannot be fulfilled due to bad syntax.'
  },
  '401' : {
    title : 'Unauthorized',
    text  : 'Authentication is possible but has failed or not yet been provided.'
  },
  '403' : {
    title : 'Forbidden',
    text  : 'The request was a legal request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference.'
  },
  '404' : {
    title : 'Server is unavailable',
    text  : 'Check your internet connection.'
  },
  '500' : {
    title : 'Internal Server Error',
    text  : 'A generic error message, given when no more specific message is suitable.'
  },
  'unauthorized' : {
    title : 'Unauthorized',
    text  : 'Invalid email or password.'
  },
  'invalidxhr' : {
    title : 'Invalid client',
    text  : 'Unsupport XMLHTTPRequest object.'
  }
};

function onLoadMobileClient () {
  var $body = $(document.body).addClass('mobile-client');
  $body.find('.active-link').removeClass('active-link');
  $body.removeClass('show-splash');
}

function appendMobileClient (url) {
  if (mobileClient) {
    mobileClient.parentNode.removeChild(mobileClient);
  }

  mobileClient = document.createElement('iframe');
  document.body.appendChild(mobileClient);
  mobileClient.setAttribute('src', url);
  mobileClient.className = 'mobile-client-frame';
  mobileClient.onload = onLoadMobileClient;
}

function validAuthData ($form, data) {
  var value = null, invalidValue = false;
  for (var fld in data) {
    value = data[fld];
    switch (fld) {
      case 'email' :
        if (!value) {
          invalidValue = true;
          $form.find('input.input-text.login:first').addClass('invalid-field');
        }
        break;
      case 'password' :
        if (!value) {
          invalidValue = true;
          $form.find('input.input-text.password:first').addClass('invalid-field');
        }
    }
  }
  return !invalidValue;
}

function successAuthPost (xhr) {
  var response = null;
  try {
    response = JSON.parse(xhr.responseText);
  } catch (err) {
    errorAuthPost(xhr, err.message);
    return undefined;
  }

  var
    locationhref = encodeURIComponent(location.href),
    domain = '',
    portals = response,
    portalsInd = portals.length;
  while (portalsInd--) {
    domain = portals[portalsInd].link;
    domain = domain.lastIndexOf('/') !== -1 ? domain.substring(0, domain.lastIndexOf('/')) : domain;
    domain = domain.replace('http://', '');
    portals[portalsInd].domain = domain;
    portals[portalsInd].location = locationhref;
  }
  portals.unshift({
    name : 'Teamwork & Project Management Lab',
    logo : 'http://static.teamlab.com/studio/tag/i5.5.10/skins/default/images/logo.png',
    link : 'http://192.168.3.228:8080/mobile?asc_auth_key=',
    domain : '192.168.3.228:8080',
    location : locationhref
  });
  renderPortals(portals);
  save();
}

function showError (title, message) {
  $('#message').find('span.inner-title:first').text(title);
  $('#message').find('span.inner-text:first').text(message);
  $('#message').show();
  $(document.body).one('click', function () {
    $('#message').hide();
  });
}

function unauthorizedAuthPost (xhr) {
  $('#authForm').find('input.input-text.password:first').addClass('invalid-field');
  if (statusMessages.hasOwnProperty('unauthorized')) {
    showError(statusMessages.unauthorized.title, statusMessages.unauthorized.text);
  }
}

function unvalidObject (xhr) {
  if (statusMessages.hasOwnProperty('invalidxhr')) {
    showError(statusMessages.invalidxhr.title, statusMessages.invalidxhr.text);
  }
}

function errorAuthPost (xhr, title, message) {
  if (typeof message === 'string') {
    showError(title, message);
    return undefined;
  }

  switch (xhr.status) {
    case 401  :
      unauthorizedAuthPost(xhr);
      break;
    case 403  :
      unauthorizedAuthPost(xhr);
      break;
    case 0    :
    case 404  :
    case 400  :
    case 500  :
      if (statusMessages.hasOwnProperty('' + xhr.status)) {
        showError(statusMessages['' + xhr.status].title, statusMessages['' + xhr.status].text);
      }
      break;
    default   :
      showError(statusMessages['-1'].title, statusMessages['-1'].text);
      break;
  }
}

function getPostParams (data) {
  var params = [];
  for (var fld in data) {
    params.push(fld + '=' + data[fld]);
  }
  return params.join('&');
}

function sendAuthPost (data) {
  xhr = null;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  }

  if (!xhr) {
    unvalidObject(xhr);
    return undefined;
  }

  xhr.onreadystatechange = (function (xhr) {
    return function () {
      if (xhr.readyState === 4) {
        $('#authForm').removeClass('processing');
        switch (xhr.status) {
          case 200  :
          case 201  :
          case 202  :
            successAuthPost(xhr);
            break;
          default :
            errorAuthPost(xhr);
            break;
        }
        xhr = null;
        delete xhr;
      }
    };
  })(xhr);

  xhr.open('POST', sso_url + (sso_url.indexOf('?') === -1 ? '?' : '&') + '_=' + Math.floor(Math.random() * 1000000), true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send(getPostParams(data));
}

function onLoginSubmit (evt) {
  var $this = $('#authForm');
  var data = {
    email : $this.find('input.input-text.login:first').removeClass('invalid-field').val(),
    password : $this.find('input.input-text.password:first').removeClass('invalid-field').val()
  };
  userLogin = data.email;
  userPassword = data.password;
  if (!validAuthData($this, data)) {
    return false;
  }
  $this.addClass('processing');
  try {
    sendAuthPost(data);
  } catch (err) {
    $this.removeClass('processing');
  }

  if (evt) {
    evt.preventDefault();
  }
  return false;
}

function save () {
  store.save({
    key : store_key,
    email : $('#txtUserLogin').val(),
    password : $('#txtUserPassword').val()
  });
}

function onDeviceReady () {
  clearTimeout(drTimeout);
  //if (navigator.network.connection.type == Connection.NONE) {
  //  document.addEventListener('online', onOnline, false);
  //} else {
  //  onOffline();
  //}
}

function onOnline () {
  isOnline = true;
}

function onOffline()
{
  isOnline = false;
}

function createStore () {
  try {
    store = !window.openDatabase ? new Lawnchair({adaptor : 'dom'}) : new Lawnchair({adaptor : 'webkit'});
  } catch (err) {
    store = window.localStorage || {};
  }

  if (store) {
    store.get(store_key, function (saved) {
      if (saved && saved.email) {
        userLogin = saved.email;
        $('#txtUserLogin').val(userLogin);
      }

      if (saved && saved.password) {
        userPassword = saved.password;
        $('#txtUserPassword').val(userPassword);
      }

      $('#authForm').addClass('processing');
      renderAuthForm();
      clearTimeout(taTimeout);
      if (userLogin && userPassword) {
        onLoginSubmit();
      } else {
        taTimeout = setTimeout(function () {$('#authForm').removeClass('processing')}, 1000);
      }
    });
  }
}

$(document.body).removeClass('show-splash');
$('a.active-link').removeClass('active-link');

createStore();
$(function () {
  //createStore();
  document.addEventListener("deviceready", onDeviceReady, false);
  drTimeout = setTimeout(onDeviceReady, 1000);

  window.addEventListener("online", onOnline, false);
  window.addEventListener("offline", onOffline, false);
  if (navigator.onLine) {
    onOnline();
  } else {
    onOffline();
  }

  $(document.body).removeClass('show-splash');
  $('a.active-link').removeClass('active-link');
  $('#authForm').bind('submit', onLoginSubmit);

  $('#authForm').addClass('processing');
  renderAuthForm();
  clearTimeout(taTimeout);
  if (userLogin && userPassword) {
    onLoginSubmit();
  } else {
    taTimeout = setTimeout(function () {$('#authForm').removeClass('processing')}, 1000);
  }
});

function target_logout (evt) {
  userLogin = '';
  userPassword = '';
  $('#txtUserLogin').val(userLogin);
  $('#txtUserPassword').val(userPassword);
  save();

  renderAuthForm();
}

function target_login (evt) {
  clearTimeout(cpTimeout1);
  clearTimeout(cpTimeout2);

  var gotoPortal = this.getAttribute('href');
  if (gotoPortal) {
    var $splash = $('#splash');
    var title = this.getAttribute('data-title');
    $splash.find('.value').text(title);
    $(document.body).removeClass('show-splash');
    $splash.css('marginTop', -($splash.height() >> 1) + 'px');
    $(document.body).find('.active-link').removeClass('active-link');
    
    $(this).addClass('active-link').parent().siblings().children().removeClass('active-link');
    //location.href = gotoPortal;
    //appendMobileClient(gotoPortal);
    cpTimeout1 = setTimeout(function () {jQuery(document.body).addClass('show-splash');jQuery('.active-link').removeClass('active-link')}, 1000);
    cpTimeout2 = setTimeout(function () {window.open(gotoPortal, '_self')}, 2000);
  }
}

function onBodyMoveEvent (evt) {
  wasMoved++;
}

function onButtonStartEvent (evt) {
  $(this).addClass('active');
}

function onButtonStopEvent (evt) {
  $(this).removeClass('active');
}

function onLinkStartEvent (evt) {
  $(this).addClass('active');
  wasMoved = 0;
  startClickedObject = this;
  startEventTimestamp = new Date().getTime();
}

function onLinkStopEvent (evt) {
  var $this = $(this);
  $this.removeClass('active');
  $(startClickedObject).removeClass('active');
  //if (wasMoved === false && startClickedObject === this) {
  if (startClickedObject === this && (((wasMoved < 2) && (new Date().getTime() - startEventTimestamp < eventTimestamp)) || ($this.hasClass('ui-btn') || $this.hasClass('nav-menu-item')))) {
    return onLinkClick.apply(this, [evt]);
  }
}

function onLinkClick (evt) {
  var
    classitem = '',
    classes = this.className.split(/\s+/),
    classesInd = classes ? classes.length : 0;
  while (classesInd--) {
    classitem = classes[classesInd].replace(/-/g, '_');
    if (typeof window[classitem] === 'function') {
      window[classitem].apply(this, [evt]);
    }
  }
}

function onLinkNoneClick (evt) {
  evt.preventDefault();
  return false;
}

function setEvents ($o) {
  $(document.body).unbind(touchMoveEvent, onBodyMoveEvent).bind(touchMoveEvent, onBodyMoveEvent);
  //$o.find('a').unbind('click', onLinkClick).bind('click', onLinkClick);

  $o.find('a')
    .unbind(touchClick, onLinkNoneClick).bind(touchClick, onLinkNoneClick)
    .unbind(touchStartEvent, onLinkStartEvent).bind(touchStartEvent, onLinkStartEvent)
    .unbind(touchStopEvent, onLinkStopEvent).bind(touchStopEvent, onLinkStopEvent);

  $o.find('button')
    .unbind(touchStartEvent, onButtonStartEvent).bind(touchStartEvent, onButtonStartEvent)
    .unbind(touchStopEvent, onButtonStopEvent).bind(touchStopEvent, onButtonStopEvent);
}

function renderPage (templId, data) {
  var $page = $('div.ui-page[data-id="' + templId + '"]');
  if ($page.length === 0 || $('#' + templId).length > 0) {
    $page = $('#' + templId).tmpl(data || {});
    $page.attr('data-id', templId);
    $wrapper.append($page);
  }
  setEvents($page);
  $page.addClass('active');
  $wrapper.children('div.ui-page.active').not($page).removeClass('active');
  return $page;
}

function renderAuthForm () {
  //Render auth form
  renderPage('pg-auth', {});
}

function renderPortals (portals) {
  //Render portals
  var $page = renderPage('pg-portals', {title : userLogin, items : portals});
  $(document.body).removeClass('show-splash');
  $page.find('a.active-link').removeClass('active-link');
}
